import { createRouter, createWebHistory } from 'vue-router'
import { getToken } from '@/utils/auth.js'
import { useRouterStore } from '@/stores/modeles/router.js'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/login/index.vue'),
    },
    //在这添加子路由
    {
      path: '/',
      name: 'dashboard',
      component: () => import('@/views/dashboard/index.vue'),
      children: [
        {
          path: '/detail',
          name: 'detail',
          component: () => import('@/views/entrance/detail.vue'),
        },
      ],
    },
    {
      path: '/404',
      name: '404',
      component: () => import('@/views/NotFound.vue'),
      meta: { noAuth: true },
    },
    {
      path: '/:pathMatch(.*)',
      name: 'notFound',
      hidden: true,
      redirect: '/404',
    },
  ],
})

//守卫
router.beforeEach((to, from, next) => {
  const hasToken = getToken()
  if (to.name == 'login') {
    next()
  } else {
    if (hasToken) {
      const routerStore = useRouterStore()
      if (!routerStore.$state.isHaveRouter) {
        //登录后还未获取动态路由
        routerStore.setRouter().then(() => {
          // 这里是核心代码，因为第一次匹配不到会跳转404
          // 所以跳转到404的时候再做一个操作
          if (to.path == '/404' && to.redirectedFrom) {
            next({ path: to.redirectedFrom.fullPath, replace: true })
          } else {
            next({ ...to, replace: true }) // 这里相当于push到一个页面 不在进入路由拦截
          }
        })
      } else {
        next()
      }
      // next()
    } else {
      next({ path: '/login' })
    }
  }
})

export default router
